export default function fileDownload(url: string, filename: string, xml: boolean, params?: {}) {
    if (!xml) {
        let a: HTMLElement | null = document.createElement('a');
        a.setAttribute('href', url);
        a.setAttribute('download', filename);
        a.click();
        a = null;
        return;
    }
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
            if (this.status === 200) {
                xhr.responseType = 'blob';
            }
        }
    }
    xhr.onload = function () {
        if (this.status === 200) {
            if (this.response.type.startsWith('text')) {
                let reader = new FileReader();
                reader.readAsText(this.response);
            } else {
                let type = xhr.getResponseHeader('Content-Type');
                let blob = new Blob([this.response], {type: type as string | undefined});
                let URL = window.URL || window.webkitURL;
                let objectUrl = URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = objectUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
                URL.revokeObjectURL(objectUrl);
            }
        }
    }
    if (params) {
        let keys = Object.keys(params);
        let data = keys.length !== 0 ? keys[0] + "=" + params[keys[0]] : "";
        for (let i = 1; i < keys.length; i++) {
            let key = keys[i];
            data += "&" + key + "=" + encodeURIComponent(params[key]);
        }
        xhr.send(data);
    }
    xhr.send();
}